/**   
* @Title: JerseyService.java 
* @Package: com.ifuntimes.http
* @Description: TODO
* @author:YuHai
* @Email: it@ifuntimes.com  
* @date 2017年09月07日 下午10:52:00 
* @version V1.0   
*/
package com.ifuntimes.http;

import java.net.InetAddress;
import java.net.URI;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.core.UriBuilderException;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.servlet.ServletContainer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ifuntimes.exception.ServiceException;
import com.ifuntimes.utils.LocalIpAddressUtil;


/**
 * @ClassName: JerseyService
 * @Description: JerseyService
 * @author YuHai it@ifuntimes.com  
 * @date 2017年09月07日 下午10:52:00
 * 
 */

public class JerseyService implements Runnable {

	private final static Logger logger = LoggerFactory.getLogger(JerseyService.class);

	/*
	 * (非 Javadoc) <p>Title: run</p> <p>Description: </p>
	 * 
	 * @see java.lang.Runnable#run()
	 */

	@Override
	public void run() {
		logger.info("Start embedded Jetty HTTPServer...\n");
		try {
			Server server = createHttpServer();
			server.start();
			server.join();
			for (int i = 0; i < this.getHostsIps().size(); i++) {
				logger.info(String.format(
						"\nJersey Application Server started with WADL available at " + "%sapplication.wadl\n",
						this.getCrunchifyURI().get(i)));
			}

			logger.info("Start embedded Jetty HTTPServer successfully...");
		} catch (Exception e) {
			logger.error("", e);
		}
	}

	private Server createHttpServer() throws ServiceException {
		ResourceConfig resourceConfig = new HttpResourceConfig();
		ServletContainer servletContainer = new ServletContainer(resourceConfig);
		ServletHolder sh = new ServletHolder(servletContainer);
		Server server = new Server(ServerConfig.getJerseyPort());
		ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
		context.setContextPath("/");
		context.addServlet(sh, "/*");
		server.setHandler(context);
		return server;
	}

	/**
	 * 
	 * @Title: getCrunchifyURI
	 * @Description: Create URI
	 * @return URI
	 * @throws ServiceException 
	 * @throws UriBuilderException 
	 * @throws IllegalArgumentException 
	 */
	private List<URI> getCrunchifyURI() throws IllegalArgumentException, UriBuilderException, ServiceException {
		List<URI> uris = new ArrayList<>();
		for (int i = 0; i < this.getHostsIps().size(); i++) {
			uris.add(UriBuilder.fromUri("http://" + this.getHostsIps().get(i) + "/").port(ServerConfig.getJerseyPort())
					.build());
		}
		return uris;
	}

	/**
	 * 
	 * @Title: crunchifyGetHostName
	 * @Description: get host name
	 * @return String
	 */
	private List<String> getHostsIps() {
		Set<InetAddress> sets = LocalIpAddressUtil.resolveLocalAddresses();
		Iterator<InetAddress> iterator = sets.iterator();
		List<String> list = new ArrayList<>();
		while (iterator.hasNext()) {
			InetAddress inetAddress = iterator.next();
			list.add(inetAddress.toString().replace("/", ""));
		}
		return list;
	}
}
